var requetNet = require('../../utils/request.js');
var requetNet = require('../../utils/util.js');
var app = getApp()
const baseUrl = app.globalData.baseUrl;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    address: '',
    latitude: '',
    longitude: '',
    cart: [],
    productId: [],
    switchs: true,
    formatId: '',
    timeIndex: '',
    deliveryTime: [{
        id: 1,
        title: '当天下午15:00~17:00(单天16：00前下单选此项)'
      },
      {
        id: 2,
        title: '次日早上09:00~12:00(单天16：00后下单选此项)'
      },
      {
        id: 3,
        title: '自提'
      }
    ],
    cart: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(option) {
    var that = this;
    console.log("option:", option)
    that.setData({
      productId: option.productId ? option.productId : '',
      formatId: option.formatId ? option.formatId : '',
      count: option.count ? option.count : ''
    })
    console.log(" formatId:", this.data.formatId)
    console.log(" count:", this.data.count)
    //地址
    that.setData({
      cart: wx.getStorageSync("cart") ? JSON.parse(wx.getStorageSync("cart")) : [],
      product: wx.getStorageSync("product") ? JSON.parse(wx.getStorageSync("product")) : {}
    })
    this.setData({
      formatTitle: wx.getStorageSync("formatTitle")
    })
    console.log("点击购物车支付", this.data.cart);
    console.log("点击立刻购买支付商品", this.data.product);
    console.log("点击立刻购买支付商品规格", wx.getStorageSync("formatTitle"));
    this.getTotalPrice(); //计算支付总价
  },
  getTotalPrice() {
    let cart = this.data.cart; // 获取购物车列表
    let total = 0;
    let numcount = 0;
    for (let i = 0; i < cart.length; i++) { // 循环列表得到每个数据
      total += cart[i].count * cart[i].formatPrice; // 所有价格加起来
      numcount += Number(cart[i].count);
    }
    this.setData({ // 最后赋值到data中渲染到页面
      cart: cart,
      totalPrice: total,
      numcount: numcount
    });
  },
  switch1Change(e) {
    var that = this;
    that.setData({
      switchs: e.detail.value
    })
    console.log('switch发生 change 事件，携带值为', e.detail.value)
  },

  //地址
  getLocation: function() {
    var that = this;
    wx.chooseAddress({
      success(res) {
        var address = res.provinceName + res.cityName + res.countyName + res.detailInfo
        console.log(address)
        that.setData({
          detailInfo: res.detailInfo,
          telNumber: res.telNumber,
          provinceName: res.provinceName,
          cityName: res.cityName,
          countyName: res.countyName,
          address: address
        })
      }
    })
  },
  settime: function(e) {
    this.setData({
      timeIndex: e.currentTarget.dataset.timeindex,

    })
  },
  goAgreement: function(e) {
    // wx.navigateTo({
    //   url: '',
    // })
  },
  //支付
  payfor() {
    console.log(this.data.timeIndex)
    if (this.data.switchs == false) { //没有同意协议
      wx.showToast({
        title: '请阅读协议信息，并同意',
        icon: 'none',
        duration: 1000,
        mask: true
      })
    } else if (!this.data.address) {
      wx.showToast({
        title: '请填写收货地址！',
        icon: 'none',
        duration: 1000,
        mask: true
      })

    } else if (this.data.timeIndex === '') {
      wx.showToast({
        title: '请选择配送时间！',
        icon: 'none',
        duration: 1000,
        mask: true
      })
    } else {
      //商品支付
      console.log("商品支付Id：", this.data.product[0].id)
      console.log("formatId:", this.data.formatId)
      var that = this;
      //判断
      if (!this.data.productId) {
        var url = baseUrl + '/yq/order/payCart';
        var cart = new Array;
        for (let i = 0; i < this.data.cart.length; i++) {
          cart.push({
            "productId": this.data.cart[i].productId,
            "formatId": this.data.cart[i].formatId,
            "count": this.data.cart[i].count
          })
        }
        console.log(cart)
        var params = {
          cart: cart,
          extraInfo: this.data.deliveryTime[this.data.timeIndex].title
        }
      } else {
        var url = baseUrl + '/yq/order/pay';
        var params = {
          productId: this.data.product[0].id,
          formatId: this.data.formatId,
          extraInfo: this.data.deliveryTime[this.data.timeIndex].title
        };
      }
      var success = res => {
        that.setData({
          requestpayment: res.info
        })
        console.log("支付参数获取成功：", res)
        wx.requestPayment({
          timeStamp: '' + this.data.requestpayment.timeStamp,
          nonceStr: '' + this.data.requestpayment.nonce_str,
          package: 'prepay_id=' + this.data.requestpayment.package,
          signType: 'MD5',
          paySign: '' + this.data.requestpayment.sign,
          success(res) {
            wx.redirectTo({
              // url: '../orderdetails/orderdetails',
              url: '/pages/success/success'
            })
          },
          fail(res) {
            wx.showToast({
              title: '支付失败',
              icon: 'none',
              duration: 1000,
              mask: true
            })
          }
        })
      }
      var fail = res => {
        console.log("支付参数获取失败：", res)
      }
      app.request(url, params, success, fail);

    }
  }


})